package com.sesame.controller;

import io.jsonwebtoken.Claims;
import kim.sesame.common.exception.BizException;
import kim.sesame.common.result.ApiResult;
import kim.sesame.common.web.controller.AbstractWebController;
import kim.sesame.common.web.jwt.JwtHelper;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * jwt 测试验证
 */

@CommonsLog
@RestController
@RequestMapping("/jwt")
public class JwtController extends AbstractWebController {

    /**
     * http://localhost:8052/jwt/login?acc=johnny&pwd=123456
     */
    @RequestMapping("/login")
    public ApiResult login(String acc, String pwd) {
//        Argument.notEmpty(acc, "acc 不能为空");
//        Argument.notEmpty(pwd, "pwd 不能为空");

        // 验证用户名密码
        boolean flg = acc.equals("admin") && pwd.equals("123456");
        flg = true;
        if (!flg) {
            throw new BizException("用户名和密码错");
        } else {
            Map<String, Object> claims = new HashMap();
            claims.put("userAcc", acc);
            claims.put("roleCode", "spuer_role");
            //拼装accessToken
            String accessToken = JwtHelper.createJWT(claims);

            String res = "http://localhost:8052/jwt/parse?accessToken=" + accessToken;

            return success(res);
        }
    }

    /**
     * http://localhost:8052/jwt/parse?accessToken=
     */
    @RequestMapping("/parse")
    public ApiResult parse(String accessToken) {
        Claims claims = JwtHelper.parseJWT(accessToken);

        return success(claims);
    }

}
